const Koa = require('koa')
const path = require('path')
const koaRouter = require('koa-router')()
// const bodyParser = require('koa-bodyparser')
const bodyParser = require('koa-body')
const staticFiles = require('koa-static') // 配置静态资源路径的库
const cors = require('koa2-cors')
const session = require('koa-session')
const fs = require('fs')

// 路由引入
const home = require('./server/home')
const register = require('./server/register')
const login = require('./server/Login')
const goods = require('./server/goods')
const getAuthcode = require('./server/getAuthcode')
const upload = require('./server/upload')
const empty = require('./server/empty')
const update = require('./server/update')
const cart = require('./server/cart')
const test = require('./server/test')
const order = require('./server/order')
const pay = require('./server/pay')
const imgUpload = require('./server/imgUpload')
const evaluate = require('./server/evaluate')
// const index = require('./server/index')
const { InitSchema, connect } = require('./db/connect')
const app = new Koa()

app.keys = ['some secret hurr'] // 密钥
const CONFIG = {
  key: 'koa.sess',
  maxAge: 86400000,
  autoCommit: true,
  overwrite: true,
  // httpOnly: true,
  signed: true,
  rolling: false,
  // secure: true,
  sameSite: null
}

// const { historyApiFallback } = require('koa2-connect-history-api-fallback')
// // handle fallback for HTML5 history API
// // 这个库会从配置的静态资源文件夹下去找index.html这个文件
// app.use(historyApiFallback({ index: '/index.html' }))
// 这是支持跨域的模块
app.use(cors({
  credentials: true
}))
app.use(session(CONFIG, app));
// 开启数据库服务端于数据库的连接 以及将表导入好使用
(async () => {
  await connect()
  InitSchema()
})()

// koaRouter.use('', index.routes())
koaRouter.use('/goods', goods.routes())
koaRouter.use('/upload', upload.routes())
koaRouter.use('/home', home.routes())
koaRouter.use('/register', register.routes())
koaRouter.use('/login', login.routes())
koaRouter.use('/empty', empty.routes())
koaRouter.use('/update', update.routes())
koaRouter.use('/getAuthcode', getAuthcode.routes())
koaRouter.use('/cart', cart.routes())
koaRouter.use('/test', test.routes())
koaRouter.use('/order', order.routes())
koaRouter.use('/pay', pay.routes())
koaRouter.use('/imgUpload', imgUpload.routes())
koaRouter.use('/evaluate', evaluate.routes())
// render(app, {
//     root: path.join(__dirname, 'views'),
//     extname: '.html',
//     debug: process.env.NODE_ENV !== 'production'
//   });
// koaRouter.get('/',async function(cxt,next){
//     // console.log(cxt.url)
//     // // cxt.body="hello"
//     // cxt.body="cheng gon2"
//     await cxt.render('index')
//     // next()
// })

// koaRouter.get('/home/:id',async function(cxt,next){
//     console.log(cxt.query)
//     console.log(cxt.params)
//     cxt.body="cheng gon"
// })

app.use(staticFiles(path.join(__dirname, 'public')))

app.use(
  bodyParser({
    multipart: true, // 支持文件上传
    formidable: {
      // uploadDir: path.join(__dirname, 'public/uploads/'), // 设置文件上传目录
      // keepExtensions: true, // 保持文件的后缀
      // maxFieldsSize: 2 * 1024 * 1024, // 文件上传大小，缺省2M
      onFileBegin: (name, file) => { // 文件上传前的设置
        const fp = path.join(__dirname, 'public/uploads/')
        if (!fs.existsSync(fp)) { // 检查是否有“public/upload/”文件夹
          fs.mkdirSync(fp) // 没有就创建
        }
        // console.log(`bodyparse: name:${name}; file:${util.inspect(file)}`);
      }
    }
  })
)

// app.use(async function (ctx,next) {
//   console.log('111')
//   ctx.body='hhh'
//   next()
// });
// 好像next在路由之间调用,但是最后一个执行的路由好像不会调next
app.use(koaRouter.routes())
app.use(koaRouter.allowedMethods())

app.listen(5000)
